package edu.pku.sei.mte.compositetrans.flow;

import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public abstract class DecisionNode<CONDITION> extends FlowNode {

	protected FlowNode trueNode;
	protected FlowNode falseNode;
	protected CONDITION condition;
	protected boolean decision;

	@Override
	public FlowNode getNext() {
		if(isSucceed){
			if(decision)
				return trueNode;
			else return falseNode;
		}
		return FlowController.WRONG_OF_FLOW;
	}
	
	@Override
	public abstract boolean execute() throws Exception;
	
	@Override
	public void load(Element e, Map<Integer, FlowNode> FlowNodesMap) {
		NodeList nl = e.getChildNodes();
		for(int i=0;i<nl.getLength();i++){
			Node n = nl.item(i);
			if(n.getNodeType()!=Node.ELEMENT_NODE)
				continue;
			Element ee = (Element) n;
			if(ee.getTagName().equals("post")){
				FlowNode fn = FlowNodesMap.get(Integer.parseInt(ee.getAttribute("nid")));
				if(ee.getAttribute("value").equals("true"))
					trueNode = fn;
				else if(ee.getAttribute("value").equals("false"))
					falseNode = fn;
			}
		}
		if (trueNode instanceof JoinNode)
			((JoinNode)trueNode).getPreNodes().add(this);
		if (falseNode instanceof JoinNode)
			((JoinNode)falseNode).getPreNodes().add(this);
		super.load(e, FlowNodesMap);
	}
	
	public FlowNode getTrueNode() {
		return trueNode;
	}

	public void setTrueNode(FlowNode trueNode) {
		this.trueNode = trueNode;
	}

	public FlowNode getFalseNode() {
		return falseNode;
	}

	public void setFalseNode(FlowNode falseNode) {
		this.falseNode = falseNode;
	}

	public CONDITION getCondition() {
		return condition;
	}

	public void setCondition(CONDITION condition) {
		this.condition = condition;
	}

}
